package com.lmx.web.controller.thirdPart;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lmx.common.context.ActionContextHolder;
import com.lmx.common.util.CommonUtil;
import com.lmx.persistence.service.DeviceService;
import com.lmx.persistence.service.HbeaconService;

import net.sf.json.JSONObject;

/*-
 * 处理接口
 */

@Controller
@RequestMapping("/access/hbeacon")
public class HbeaconController {
	private static Log logger = LogFactory.getLog(HbeaconController.class);

	@Autowired
	protected HbeaconService hbeaconService;

	@Autowired
	protected DeviceService deviceService;

	// 获取手环按键对应关系
	@RequestMapping("/relationData")
	@ResponseBody
	public void hbeaconRelationData(HttpServletRequest request, HttpServletResponse response) {
		// 数据处理
		logger.debug(
				"-----------------------------hbeacon Relation  data   start-------------------------------------");
		String param = request.getParameter("flag");
		Long tenantId = (long) -1;
		if (param != null && !"".equals(param) && param.matches("\\d+")) {
			tenantId = Long.parseLong(param);// 获取所传tenantid
		}
		String res = hbeaconService.getHbeaconRelationData(tenantId);
		BufferedOutputStream out;
		try {
			out = new BufferedOutputStream(response.getOutputStream());
			out.write(res.getBytes());
			out.flush();
			out.close();
		} catch (IOException e) {
			logger.debug("hbeacon Relation  data  error:" + e);
		}
		logger.debug("-----------------------------hbeacon Relation  data   end-------------------------------------");
	}

	// 收取本地服务推送的设备信息
	@RequestMapping("/receiveDeviceData")
	@ResponseBody
	public void receiveDeviceData(HttpServletRequest request, HttpServletResponse response) {
		logger.debug("---------------start receive hbeacon data-------------------------------------");
		BufferedReader in = null;
		String result = "";
		try {
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(request.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
//			if("".equals(result)||result==null){
//						 result="{\"callingData\":[{\"callingTime\":1509694797,\"deviceId\":\"f096b1d1ea07\"}],\"dataSource\":\"huami\"}";//呼叫
//			}
			// result="{\"callingData\":[{\"callingTime\":1509694797,\"deviceId\":\"f096b1d1ea07\"}],\"dataSource\":\"huami\"}";//呼叫
			// result="{\"deviceData\":[{\"deviceId\":\"fx000000000\",\"dataTime\":666666},{\"deviceId\":\"fx000000001\",\"dataTime\":666666}]}";//设备数据
			// result="{\"locationData\":[{\"dataTime\":1501635355,\"scanner\":\"feffaaf074fe\",\"deviceId\":\"d8b61a48a513\"}]}";//位置数据
			logger.debug("receive data " + result);
			if (result != null && !"".equals(result)) {
				// JSONObject data = JSONObject.fromObject(result);
				if (result.contains("callingData")) {// 按键呼叫信息
					hbeaconService.buildHbeaconCallingMessage(result);// 添加socket提醒信息
				}
				if (result.contains("deviceData")) {// 设备以及信息
					deviceService.updateDeviceStatusDate(result);// 更新设备状态时间
				}
				if (result.contains("locationData")) {// 位置信息
					deviceService.updateDeviceLocationData(result);// 更新位置信息
				}
				if (result.contains("scannerStatus")) {// 扫描器状态信息
					deviceService.updateScannerStatusData(result);// 更新扫描器状态信息
				}
			}
			logger.debug("receiveDeviceData: " + result);
			BufferedOutputStream out;
			out = new BufferedOutputStream(response.getOutputStream());
			out.write("http ok".getBytes());
			out.flush();
			out.close();
		} catch (Exception e) {
			logger.debug("receiveDeviceData Exception: " + e.toString());
		} finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				logger.debug("receiveDeviceData error " + ex);
			}
		}
		logger.debug("---------------end receive hbeacon data-------------------------------------");// 数据处理
	}
	
	
	// 从按键呼叫列表中去除相应按键
	@RequestMapping("/removeCalling")
	@ResponseBody
	public void removeCallingDevice(HttpServletRequest request, HttpServletResponse response) {
		// 数据处理
		logger.debug(
				"-----------------------------remove hbeacon  data  start-------------------------------------");
		String param = request.getParameter("hid");
		if (param != null && !"".equals(param) ) {
			ActionContextHolder.getCallingList().remove(param);
		}
		BufferedOutputStream out;
		try {
			out = new BufferedOutputStream(response.getOutputStream());
			out.write("ok".getBytes());
			out.flush();
			out.close();
		} catch (IOException e) {
			logger.debug("remove hbeacon  data   error:" + e);
		}
		logger.debug("-----------------------------remove hbeacon  data    end-------------------------------------");
	}
	
	
	// 接受本地服务心跳
	@RequestMapping("/receiveLocalFlag")
	@ResponseBody
	public void receiveLocalFlag(HttpServletRequest request, HttpServletResponse response) {
		// 数据处理
		logger.debug("-----------------------------receiveLocalFlag  start-------------------------------------");
		BufferedReader in = null;
		String result = "";
		try {
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(request.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
			logger.debug("receive data " + result);
			if (result != null && !"".equals(result)) {
				 JSONObject data = JSONObject.fromObject(result);
				if (data.containsKey("localFlag")) {
					ActionContextHolder.getLocalServerFlag().put(data.getString("localFlag"),
							CommonUtil.getCurrTimes());
				}
			}
			logger.debug("receiveDeviceData: " + result);
			BufferedOutputStream out;
			out = new BufferedOutputStream(response.getOutputStream());
			out.write("http ok".getBytes());
			out.flush();
			out.close();
		} catch (Exception e) {
			logger.debug("receiveDeviceData Exception: " + e.toString());
		} finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				logger.debug("receiveLocalFlag error " + ex);
			}
		}
		logger.debug("-----------------------------receiveLocalFlag    end-------------------------------------");
	}
}
